package com.xbongbong.crm.service.permission;

import com.xbongbong.crm.help.PublicHelp;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.util.ElasticSearchConditionUtil;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.parent.abstracts.AbstractBusinessPermissionService;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.pro.statistic.result.pojo.ElasticAggsPojo;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.util.UserPermissionUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/02/08 17:10
 */
@Service("customerPermissionServiceImpl")
public class CustomerPermissionServiceImpl extends AbstractBusinessPermissionService<PaasFormDataEntityExt, PaasFormEntityExt> {

    @Resource
    private EsHelper esHelper;
    @Resource
    private PublicHelp publicHelp;
    @Resource
    private IndexTypeModel indexTypeModel;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.CUSTOMER_DEAL.getCode(), XbbRefTypeEnum.CUSTOMER_FOCUS.getCode(), XbbRefTypeEnum.CUSTOMER_FOLLOW.getCode(), XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode());
    }

    @Override
    public void checkPermission(PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, UserVO loginUser, Integer subBusinessType) throws XbbException {
        VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(loginUser, paasFormDataEntityExt);
        boolean hasDataPermission = hasPermission(formEntity, paasFormDataEntityExt, loginUser, subBusinessType)
                || sharePermissionHelp.verifySharePermission4QueryWithRuleEngine(verifyViewPermissionDTO);
        if (!hasDataPermission) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
        }
    }

    @Override
    public boolean checkDelPermission(List<String> userIdIn, PaasFormDataEntityExt paasFormDataEntityExt, Integer businessType) throws XbbException {
        UserTeamEnum byCode = UserTeamEnum.getByCode(businessType);
        BoolQueryBuilder boolQueryBuilder = ElasticSearchConditionUtil.permissionQueryIsMain(paasFormDataEntityExt.getId(), userIdIn, paasFormDataEntityExt.getCorpid(), byCode.getIndexTypeEnum());
        return checkPermissionByTeam(paasFormDataEntityExt.getCorpid(), businessType, boolQueryBuilder);
    }



    @Override
    public Boolean checkPermissionByTeam(String corpid, Integer businessType, BoolQueryBuilder boolQueryBuilder) throws XbbException {
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        return checkPermissionByTeam(boolQueryBuilder, indexTypeEnum);
    }

    @Override
    public boolean hasPermission(PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, UserVO loginUser, Integer subBusinessType) throws XbbException {
        if (UserPermissionUtil.isMaxDataPermission(loginUser, formEntity.getSaasMark(), formEntity.getBusinessType(), formEntity.getDistributorMark(), formEntity.getMenuId(), false)){
            return true;
        }
        // com.xbongbong.saas.help.SaasDetailPermissionHelp.checkPermission

        String corpid = paasFormDataEntityExt.getCorpid();
        Long dataId = paasFormDataEntityExt.getId();
        List<String> userIdIn = getUserIdIn(loginUser);

//        !Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_RECYCLE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.WORK_ORDER_ROB.getCode())
//                && !Objects.equals(subBusinessType, XbbRefTypeEnum.ONLINE_PAYMENT_FLOW.getCode())
        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode(), subBusinessType)) {
            return true;
        }
        if (Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel())){
            //回收站客户就不区分了
            return true;
        }
        boolean hasPermission;
        if (Objects.equals(paasFormDataEntityExt.getData().getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr()),1)){
            //低权限公海校验
            hasPermission = publicHelp.publicCustomerCheck(loginUser, paasFormDataEntityExt.getDataId(),paasFormDataEntityExt.getFormId(), formEntity.getBusinessType());
            hasPermission = hasPermission && ProPermissionHelp.hasThisPermission(loginUser, ProPermissionAliasEnum.CUSTOMER_PUBLIC.getAlias());
            if (!hasPermission) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
            }
            return true;
        }

        BoolQueryBuilder boolQueryBuilder = ElasticSearchConditionUtil.permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_CUSTOMER_TEAM);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(indexTypeEnum, boolQueryBuilder, null);
        return StringUtil.toInt(elasticAggsPojo.getTotal(), 0) > 0;
    }
}
